package com.ybt.service.impl.base;

import java.util.Properties;

import org.apache.log4j.Logger;

import com.ruleengine.context.IContextProperty;
import com.ruleengine.context.IWorkflowConext;
import com.ruleengine.endpoint.data.IEndpointData;
import com.ybt.context.IYBTContextConstants;
import com.ybt.context.util.ContextUtil;
import com.ybt.pub.ObjectSerializationUtil;
import com.ybt.router.client.MessageClient;
import com.ybt.router.core.message.IMSDMessageConstants;
import com.ybt.service.callback.IServiceCallback;
import com.ybt.service.exception.ServiceException;
import com.ybt.service.impl.NonBlockingBaseService;

/**
 * 路由服务服务.
 * 路由服务用于将服务从接入容器，转发到业务服务容器。
 * 
 * @author AB033862 Jul 31, 2012
 */
public class RouterService extends NonBlockingBaseService {
    private static Logger logger = Logger.getLogger(RouterService.class);
    @Override
    public void serviceNonBlocking(IWorkflowConext context, IEndpointData data,
            IServiceCallback callback) throws ServiceException {
        String service = null;
        try {
            // 银保通服务
            IContextProperty<String> servicep = context
                    .getContextProperty(IYBTContextConstants.YBT_SERVICE);
            service = servicep.getValue();

            // 银保通渠道
            IContextProperty<String> channelp = context
            .getContextProperty(IYBTContextConstants.YBT_CHANNEL);
            String channel = channelp.getValue();
            if(logger.isDebugEnabled()){
                logger.debug("route service ["+service+"] in channel ["+channel+"]...");
            }
            
            // 拷贝消息头
            Properties p = ContextUtil.getSeriPropertys(context);
            p.setProperty(IMSDMessageConstants.MSD_FROM, channel);
            p.setProperty(IMSDMessageConstants.MSD_TO, service);
            p.setProperty(IMSDMessageConstants.MSD_DESTINATION,service);

            // 拷贝消息体
            IContextProperty<Object> dataPro = context
                    .getContextProperty(IYBTContextConstants.ORIGINAL_DATA);
            byte[] body = dataPro.getValue() == null ? new byte[0]
                    : ObjectSerializationUtil.toByte(dataPro.getValue());

            //
            
            // 发送消息
            MessageClient.getInstance().sendOneWay(body, p);

        } catch (Exception e) {
            throw new ServiceException("route the service ["
                    + service
                    + "] error", e);
        }
    }

}
